package com.example.demo.service;

import com.example.demo.pojo.Order;
import org.mengyun.tcctransaction.api.Compensable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ConsumerService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private BookService bookService;

    @Compensable(confirmMethod = "confirmOrder", cancelMethod = "cancelOrder", asyncConfirm = true)
//    @Transactional
    public void bugBook(Order order){
        Integer id = jdbcTemplate.queryForObject("select max(id) from my_order", Integer.class);
        order.setId(null == id ? 1 : id + 1);
        jdbcTemplate.execute("insert into my_order (id, user_id, book_id, num, status) values ("
                +order.getId()+","+order.getUserId()+","+order.getBookId()+","+order.getNum()+", 0)");
        bookService.bugBook(order);
        System.out.println(1/0);

    }

    public void confirmOrder(Order order){
        System.out.println("正常提交数据。。。。");
        jdbcTemplate.execute("update my_order set status = 1 where id = "+order.getId());
    }

    public void cancelOrder(Order order){
        System.out.println("错误异常数据。。。。");
        // 删除本地订单
        jdbcTemplate.execute("delete from my_order where id = "+order.getId());
        // 回滚商品服务中的数据
        bookService.cancelBook(order);
    }


//    @Compensable(confirmMethod = "confirmCreateOrder", cancelMethod = "cancelCreateOrder", asyncConfirm = true)
//    @Transactional
//    public void bugBook(Integer userId, Integer bookId){
//
//        var l = jdbcTemplate.queryForList("select * from book");
//        System.out.println(1/0);
//    }
//
//    public void confirmCreateOrder(Integer userId, Integer bookId){
//        System.out.println("正常提交数据。。。。");
//    }
//
//    public void cancelCreateOrder(Integer userId, Integer bookId){
//        System.out.println("错误异常数据。。。。");
//    }
}
